﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Yichat.MicroService.Interface;
using Yichat.MicroService.Model;

namespace Yichat.MicroService.ServiceInstance.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class CacheController : Controller
    {
        private readonly ILogger<UsersController> _logger;
        private readonly IDistributeionCache _distributeionCache;
        private readonly IUserService _userService;
        private IConfiguration _configuration;

        public CacheController(ILogger<UsersController> logger,
            IDistributeionCache distributeionCache,
            IConfiguration configuration,
            IUserService userService)
        {
            _logger = logger;
            _distributeionCache = distributeionCache;
            _configuration = configuration;
            _userService = userService;
        }

        [HttpGet]
        [Route("get")]
        public async Task<User> GetAsync([FromQuery] string key)
        {
            var cache = await _distributeionCache.GetAsync<User>(key);
            return cache;
        }

        [HttpGet]
        [Route("set")]
        public async Task SetAsync([FromQuery] string key)
        {
            var user = _userService.GetUsers().FirstOrDefault(f=>f.Name == key);
            await _distributeionCache.SetAsync(key, user, TimeSpan.FromHours(1));
        }
    }
}
